const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs-extra');
const cors = require('cors');

const app = express();
const PORT = 8004;

// 中间件配置
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 编码处理中间件
app.use((req, res, next) => {
  // 设置响应头，确保UTF-8编码
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  
  // 处理URL编码
  if (req.url) {
    try {
      req.url = decodeURIComponent(req.url);
    } catch (e) {
      // 解码失败，保持原样
    }
  }
  
  next();
});

// 根据操作系统设置上传目录
const os = require('os');
let uploadDir;
if (os.platform() === 'win32') {
  uploadDir = 'C:\\files';
} else {
  uploadDir = '/data/files';
}

// 确保上传目录存在
fs.ensureDirSync(uploadDir);

// 配置multer用于文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 处理文件名编码，避免乱码
    let originalName = file.originalname;
    
    // 处理中文文件名编码 - 多种编码格式处理
    if (Buffer.isBuffer(originalName)) {
      originalName = originalName.toString('utf8');
    } else if (typeof originalName === 'string') {
      // 尝试处理可能的编码问题
      try {
        // 如果是URL编码，先解码
        if (originalName.includes('%')) {
          originalName = decodeURIComponent(originalName);
        }
        // 如果是Base64编码，尝试解码
        if (/^[A-Za-z0-9+/]*={0,2}$/.test(originalName)) {
          try {
            const decoded = Buffer.from(originalName, 'base64').toString('utf8');
            if (decoded && decoded.length > 0) {
              originalName = decoded;
            }
          } catch (e) {
            // 不是Base64编码，保持原样
          }
        }
      } catch (e) {S
        console.log('文件名编码处理失败，使用原始名称:', e.message);
      }
    }
    
    // 获取文件扩展名
    const ext = path.extname(originalName);
    
    // 生成年月日时分秒格式的时间戳
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const second = String(now.getSeconds()).padStart(2, '0');
    
    // 生成时间戳格式：YYYYMMDDHHMMSS
    const timestamp = `${year}${month}${day}${hour}${minute}${second}`;
    
    // 获取当前秒内的序号（通过检查同秒内已存在的文件）
    const getSequenceNumber = () => {
      const files = fs.readdirSync(uploadDir);
      const currentSecondFiles = files.filter(f => {
        const match = f.match(/^(\d{14})_(\d+)/);
        return match && match[1] === timestamp;
      });
      
      if (currentSecondFiles.length === 0) {
        return 1;
      }
      
      // 提取所有序号并找到最大值
      const sequences = currentSecondFiles.map(f => {
        const match = f.match(/^(\d{14})_(\d+)/);
        return match ? parseInt(match[2]) : 0;
      });
      
      return Math.max(...sequences) + 1;
    };
    
    const sequence = getSequenceNumber();
    
    // 生成最终文件名：YYYYMMDDHHMMSS_序号.扩展名
    const finalName = `${timestamp}_${sequence}${ext}`;
    
    console.log(`文件上传: 原始名称=${file.originalname}, 处理后=${finalName}`);
    cb(null, finalName);
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 50 * 1024 * 1024 // 50MB限制
  },
  fileFilter: function (req, file, cb) {
    // 允许所有文件类型
    cb(null, true);
  }
});

// 路由配置

// 主页
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 获取文件列表
app.get('/api/files', async (req, res) => {
  try {
    const files = await fs.readdir(uploadDir);
    const fileList = [];
    
    for (const file of files) {
      const filePath = path.join(uploadDir, file);
      const stats = await fs.stat(filePath);
      fileList.push({
        name: file,
        size: stats.size,
        uploadTime: stats.mtime,
        url: `/api/download/${encodeURIComponent(file)}`
      });
    }
    
    // 按上传时间排序，最新的在前
    fileList.sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime));
    
    res.json({
      success: true,
      files: fileList
    });
  } catch (error) {
    console.error('Error reading files:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to read files'
    });
  }
});

// 文件上传
app.post('/api/upload', upload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        error: 'No file uploaded'
      });
    }
    
    res.json({
      success: true,
      message: 'File uploaded successfully',
      file: {
        name: req.file.filename,
        originalName: req.file.originalname,
        size: req.file.size,
        url: `/api/download/${encodeURIComponent(req.file.filename)}`
      }
    });
  } catch (error) {
    console.error('Upload error:', error);
    res.status(500).json({
      success: false,
      error: 'Upload failed'
    });
  }
});

// 文件下载
app.get('/api/download/:filename', (req, res) => {
  try {
    const filename = decodeURIComponent(req.params.filename);
    const filePath = path.join(uploadDir, filename);
    
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        error: 'File not found'
      });
    }
    
    // 设置正确的响应头，支持中文文件名
    const stats = fs.statSync(filePath);
    let originalName = req.query.originalName || filename;
    
    // 处理下载时的文件名编码
    try {
      if (originalName.includes('%')) {
        originalName = decodeURIComponent(originalName);
      }
    } catch (e) {
      console.log('下载文件名解码失败，使用原始名称');
    }
    
    // 根据文件扩展名设置正确的Content-Type
    const ext = path.extname(originalName).toLowerCase();
    let contentType = 'application/octet-stream';
    
    const mimeTypes = {
      '.jpg': 'image/jpeg',
      '.jpeg': 'image/jpeg',
      '.png': 'image/png',
      '.gif': 'image/gif',
      '.bmp': 'image/bmp',
      '.webp': 'image/webp',
      '.pdf': 'application/pdf',
      '.txt': 'text/plain',
      '.doc': 'application/msword',
      '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      '.xls': 'application/vnd.ms-excel',
      '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      '.zip': 'application/zip',
      '.rar': 'application/x-rar-compressed',
      '.mp4': 'video/mp4',
      '.mp3': 'audio/mpeg'
    };
    
    if (mimeTypes[ext]) {
      contentType = mimeTypes[ext];
    }
    
    // 设置响应头，兼容不同浏览器的中文文件名
    res.setHeader('Content-Type', contentType);
    res.setHeader('Content-Length', stats.size);
    
    // 兼容不同浏览器的文件名编码
    const userAgent = req.headers['user-agent'] || '';
    let contentDisposition;
    
    if (userAgent.includes('Firefox')) {
      // Firefox 使用 RFC 5987 格式
      contentDisposition = `attachment; filename*=UTF-8''${encodeURIComponent(originalName)}`;
    } else if (userAgent.includes('Chrome') || userAgent.includes('Safari')) {
      // Chrome/Safari 支持 RFC 6266 格式
      contentDisposition = `attachment; filename="${originalName}"; filename*=UTF-8''${encodeURIComponent(originalName)}`;
    } else {
      // 其他浏览器使用通用格式
      contentDisposition = `attachment; filename="${originalName}"`;
    }
    
    res.setHeader('Content-Disposition', contentDisposition);
    
    const fileStream = fs.createReadStream(filePath);
    fileStream.pipe(res);
  } catch (error) {
    console.error('Download error:', error);
    res.status(500).json({
      success: false,
      error: 'Download failed'
    });
  }
});

// 删除文件
app.delete('/api/files/:filename', async (req, res) => {
  try {
    const filename = decodeURIComponent(req.params.filename);
    const filePath = path.join(uploadDir, filename);
    
    if (!await fs.pathExists(filePath)) {
      return res.status(404).json({
        success: false,
        error: 'File not found'
      });
    }
    
    await fs.remove(filePath);
    
    res.json({
      success: true,
      message: 'File deleted successfully'
    });
  } catch (error) {
    console.error('Delete error:', error);
    res.status(500).json({
      success: false,
      error: 'Delete failed'
    });
  }
});

// 获取存储统计信息
app.get('/api/stats', async (req, res) => {
  try {
    const files = await fs.readdir(uploadDir);
    let totalSize = 0;
    let fileCount = 0;
    
    for (const file of files) {
      const filePath = path.join(uploadDir, file);
      const stats = await fs.stat(filePath);
      totalSize += stats.size;
      fileCount++;
    }
    
    res.json({
      success: true,
      stats: {
        fileCount,
        totalSize,
        totalSizeMB: (totalSize / (1024 * 1024)).toFixed(2)
      }
    });
  } catch (error) {
    console.error('Stats error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to get stats'
    });
  }
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    success: false,
    error: 'Something went wrong!'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 File storage service is running on http://localhost:${PORT}`);
  console.log(`📁 Upload directory: ${uploadDir}`);
  console.log(`📊 API endpoints:`);
  console.log(`   GET  /api/files - List all files`);
  console.log(`   POST /api/upload - Upload a file`);
  console.log(`   GET  /api/download/:filename - Download a file`);
  console.log(`   DELETE /api/files/:filename - Delete a file`);
  console.log(`   GET  /api/stats - Get storage statistics`);
});
